#!/usr/bin/perl
package NotesService;
push (@INC , "D:/workplace/Apache2/mason/Model");
use strict;
use warnings;
use DBI;

my $host = "localhost";         # 主机地址
my $driver = "mysql";           # 接口类型 默认为 localhost
my $database = "test";        # 数据库
# # 驱动程序对象的句柄
my $dsn = "DBI:$driver:database=$database:$host";
my $db_userid = "root";            # 数据库用户名
my $db_password = "root";        # 数据库密码

# 连接数据库
our $dbh = DBI->connect($dsn, $db_userid, $db_password ) or die $DBI::errstr;

sub new{
    my $class = shift;

    my $self = bless {}, $class;

    return $self;
};

sub list{
    my $self = shift;

    my $sth = $dbh->prepare("select * from notes where deleted_at = 0");

    $sth->execute();

    my @data_ =qw//;

    while ( my $row = $sth->fetchrow_hashref() )
    {
        my %data = ();

        $data{'id'}        = $row->{'id'};
        $data{'title'}     = $row->{'title'};
        $data{'abstract'}  = $row->{'abstract'};
        $data{'content'}   = $row->{'content'};

        push @data_, \%data;
    }

    return @data_;
};

sub detail{
    my($self, $id) = @_;

    my $sth = $dbh->prepare("select * from notes where id = ?");

    $sth->execute($id);

    my %data = ();

    while ( my $row = $sth->fetchrow_hashref() )
    {
        $data{'id'} = $row->{'id'};
        $data{'title'}  = $row->{'title'};
        $data{'abstract'}  = $row->{'abstract'};
        $data{'content'}  = $row->{'content'};
    }

    return %data;
};

sub create{
    my ($self, $params) = @_;

    my $sth = $dbh->prepare("insert into notes(title, abstract, content, created_at, updated_at) values(?,?,?,?,?)");

    $sth->execute($params->{'title'}, $params->{'abstract'}, $params->{'content'}, time(), time());

    return 1;
};

sub update{
    my ($self, $params) = @_;

    my $sth = $dbh->prepare("update notes set title=?, abstract=?, content=?, updated_at=? where id=?");

    $sth->execute($params->{'title'}, $params->{'abstract'}, $params->{'content'}, time(), $params->{'id'});

    return 1;
};

sub delete{
    my ($self, $id) = @_;

    my $sth = $dbh->prepare("update notes set deleted_at=? where id=?");

    $sth->execute(time(), $id);

    return 1;
};

1;